package com.google.samples.apps.library_common.base

import android.util.SparseIntArray
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder

/**
 * 使用方式1. BaseAdapter<T>(R.layout.item)
 * 使用方式1. 继承 BaseAdapter<T>()  init {addItemType()}
 *
 */
open abstract class BaseAdapter<T>(@LayoutRes private var layoutResId: Int = 0) : BaseQuickAdapter<T, BaseViewHolder>(layoutResId), LoadMoreModule {


    private var isMultiItem = false

    private val layouts: SparseIntArray by lazy(LazyThreadSafetyMode.NONE) { SparseIntArray() }

    override fun getDefItemViewType(position: Int): Int {

        if (isMultiItem) {
            val item = data[position]

            if (item !is MultiItemEntity) {
                // BaseAdapter<T : MultiItemEntity>
                throw RuntimeException("使用多布局需要 data 需要实现 MultiItemEntity")
            }
            return (data[position] as MultiItemEntity).itemType
        } else {
            return super.getDefItemViewType(position)
        }
    }

    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        if (isMultiItem) {
            val layoutResId = layouts.get(viewType)
            require(layoutResId != 0) { "ViewType: $viewType found layoutResId，please use addItemType() first!" }
            return createBaseViewHolder(parent, layoutResId)
        } else {
            return super.onCreateDefViewHolder(parent, viewType)
        }
    }

    /**
     * 调用此方法，设置多布局
     * @param type Int
     * @param layoutResId Int
     */
    protected fun addItemType(type: Int, @LayoutRes layoutResId: Int) {
        layouts.put(type, layoutResId)
        isMultiItem = true
    }


}